<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    <title>Shopping Cart with Remembered Checkbox State</title>
</head>
<body>

<h2>Shopping Cart</h2>

<!-- 示例商品 -->
<div class="123">
    <div class="product">
        <input type="checkbox" id="product1" name="product" data-product-id="1">
        <label for="product1">Product 1</label>
    </div>
    <div class="product">
        <input type="checkbox" id="product2" name="product" data-product-id="1">
        <label for="product2">Product 2</label>
    </div>
    <div class="product">
        <input type="checkbox" id="product3" name="product" data-product-id="1">
    </div>

</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 获取所有商品复选框元素
        const checkboxes = document.querySelectorAll('input[type="checkbox"][name="product"]');

        // 恢复上次保存的状态
        checkboxes.forEach(function(checkbox) {
            const productId = checkbox.getAttribute('data-product-id');
            const storedValue = localStorage.getItem('product_' + productId);

            if (storedValue === 'checked') {
                checkbox.checked = true;
            } else {
                checkbox.checked = false;
            }

            // 监听复选框状态变化
            checkbox.addEventListener('change', function() {
                if (checkbox.checked) {
                    localStorage.setItem('product_' + productId, 'checked');
                } else {
                    localStorage.removeItem('product_' + productId);
                }
            });
        });
    });
</script>

</body>
</html>